import 'package:fish_redux/fish_redux.dart';
import 'package:wowhy/models/admin_user_info.dart';

import '../admin_user_item_component/state.dart';
import '../action.dart';
import '../state.dart';

Reducer<AdminUserListState> buildReducer() {
  return asReducer(
    <Object, Reducer<AdminUserListState>>{
      AdminUserListAction.remove: _remove,
      AdminUserListAction.add: _add,
    },
  );
}

AdminUserListState _remove(AdminUserListState state, Action action) {
  final AdminUserInfo payload = action.payload as AdminUserInfo;

  if (payload != null) {
    final AdminUserListState newState = state.clone();
    newState.list = newState.list
        .where((k) => k.model == null || k.model.id != payload.id)
        .toList();
    return newState;
  }

  return state;
}

AdminUserListState _add(AdminUserListState state, Action action) {
  final AdminUserInfo payload = action.payload as AdminUserInfo;

  if (payload != null) {
    final AdminUserListState newState = state.clone();
    newState.list.insert(0, AdminUserItemState.fromModel(payload));
    return newState;
  }

  return state;
}
